package com.zhongkun.datahome.core.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhongkun.datahome.common.core.domain.entity.SysUser;
import com.zhongkun.datahome.common.core.domain.entity.TenantUser;
import com.zhongkun.datahome.common.enums.TenantUserStatusEnum;
import com.zhongkun.datahome.common.enums.UserStatus;
import com.zhongkun.datahome.common.utils.SecurityUtils;
import com.zhongkun.datahome.common.utils.StringUtils;
import com.zhongkun.datahome.core.mapper.SysUserMapper;
import com.zhongkun.datahome.core.mapper.TenantMapper;
import com.zhongkun.datahome.core.mapper.TenantUserMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: huangjie
 * @Date: 2025/4/14 17:15
 * @Desc
 */
@Repository
public class TenantUserRepository extends ServiceImpl<TenantUserMapper, TenantUser> {

    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private TenantMapper tenantMapper;

    public <T> void batchSetUserName(List<T> list, Function<T, Long> idValue, BiConsumer<T, String> setValue) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        Set<Long> userIdSet = list.stream().map(idValue).collect(Collectors.toSet());
        List<TenantUser> betaUserList = this.getBaseMapper().queryUserName(userIdSet);
        if (CollectionUtils.isEmpty(betaUserList)) {
            return;
        }

        Map<Long, String> userNameMap = betaUserList.stream()
                .collect(Collectors.toMap(TenantUser::getId, e -> Optional.ofNullable(e.getUserName()).orElse("")));
        for (T t : list) {
            setValue.accept(t, userNameMap.get(idValue.apply(t)));
        }
    }

    public <T> void batchSetUserName(List<T> list, Set<Long> userIdSet, BiConsumer<T, String> setValue, Function<T, Long>... idValue) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<TenantUser> betaUserList = this.getBaseMapper().queryUserName(userIdSet);
        if (CollectionUtils.isEmpty(betaUserList)) {
            return;
        }

        Map<Long, String> userNameMap = betaUserList.stream()
                .collect(Collectors.toMap(TenantUser::getId, e -> Optional.ofNullable(e.getUserName()).orElse("")));
        for (T t : list) {
            for (Function<T, Long> function : idValue) {
                setValue.accept(t, userNameMap.get(function.apply(t)));
            }
        }
    }

    public Long createTenantUser(String mobile, String customerName) {
        SysUser user = sysUserMapper.selectUserByUserName(mobile, null);
        if (Objects.isNull(user)) {
            user = new SysUser();
            user.setUserName(mobile);
            user.setNickName(customerName);
            user.setPassword(SecurityUtils.encryptPassword(mobile.substring(0, 3) + mobile.substring(mobile.length() - 3)));
            user.setPhonenumber(mobile);
            user.setUserType("customer");
            sysUserMapper.insertUser(user);
        }


        TenantUser tenantUser = getOne(new LambdaQueryWrapper<TenantUser>().eq(TenantUser::getUserId, user.getUserId()).eq(TenantUser::getTenantId, SecurityUtils.getTenantId()), false);
        if (tenantUser == null) {
            //创建租户用户
            tenantUser = new TenantUser();
            tenantUser.setUserId(user.getUserId());
            tenantUser.setTenantId(SecurityUtils.getTenantId());
            this.save(tenantUser);
        } else if (TenantUserStatusEnum.DISABLE.is(tenantUser.getStatus())) {
            tenantUser.setStatus(TenantUserStatusEnum.ENABLE.getStatus());
            this.updateById(tenantUser);
        }

        return tenantUser.getId();
    }

    public String getUserName(Long tenantUserId) {
        List<TenantUser> betaUserList = this.getBaseMapper().queryUserName(Set.of(tenantUserId));
        if (CollectionUtils.isEmpty(betaUserList)) {
            return StringUtils.EMPTY;
        }

        return betaUserList.get(0).getUserName();
    }
}
